package com.cqyc.shop.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqyc.shop.comm.StringUtil;
import com.cqyc.shop.domain.Cart;
import com.cqyc.shop.domain.Orders;
import com.cqyc.shop.services.CartServices;
import com.cqyc.shop.services.OrdersServices;

@WebServlet(urlPatterns="/jeisuan.do")
public class JieSuanServlet extends HttpServlet{
	private static final long serialVersionUID = -4401689129390874583L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	private CartServices  cartServices = new CartServices();
	private OrdersServices ordersServices = new OrdersServices();
	private SimpleDateFormat  df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("结算表演正式开始");
		try {
			//1:从前台获取参数
			String[] ids = request.getParameterValues("id");
			for(int i=0;i<ids.length;i++) {
				logger.debug("{}",ids[i]);
			}
			Cart cart = new Cart();
			//2:数据转化
			for(int i=0;i<ids.length;i++) {
				Integer idd = Integer.valueOf(ids[i]);
				cart.setId(idd);
				Cart cart2 = cartServices.findId(idd);
				request.setAttribute("cart2", cart2);
				logger.debug("{}",cart2.getShopname());
				
				String ordercode = StringUtil.generateUUID();
				//2:数据转换
				Orders orders = new Orders();
				BigDecimal howmuch  = new BigDecimal(cart2.getHowmany());
				orders.setUsercode(cart2.getUsercode());
				orders.setShopname(cart2.getShopname());
				orders.setOrdercode(ordercode);
				orders.setOrderimg(cart2.getCartimg());
				orders.setShoptime(df.format(new Date()));
				orders.setCartinfo(cart2.getCartinfo());
				orders.setPrice(cart2.getPrice().multiply(howmuch));
				orders.setHowmany(cart2.getHowmany());
				orders.setBuytotal(cart2.getBuytotal());
				
				ordersServices.save(orders);
				cartServices.delete(cart2.getId());
			}
			//3:数据校验
			//4:业务处理
			//5:跳转
			response.sendRedirect(request.getContextPath()+"/orderslist.do");
		} catch (Exception e) {
			logger.debug("{}",e.getMessage());
			request.getRequestDispatcher("/adminadd.do").forward(request, response);
		}
	}
	
}
